﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace ServiceBusAdapterTestClent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            gender.DataSource = Enum.GetNames(typeof(ServiceBusAdapter.ConstituentGenderType));
            addressAddsUpdatesDate.Value = DateTime.Now.AddHours(-2);
            endPointAddress.Text = endPointAddress.Text.Replace("[SERVER]", Environment.MachineName + ".blackbaud.com");
            userName.Text = Environment.UserName;
            domain.Text = Environment.UserDomainName;
            birthDate.Value = DateTime.Today;
        }

        private ServiceBusAdapter.ServiceBusAdapterClient GetServiceProxy()
        {
            ServiceBusAdapter.ServiceBusAdapterClient svc = new ServiceBusAdapter.ServiceBusAdapterClient(endPointConfiguration.Text, endPointAddress.Text);
            if (windowsAuth.Checked)
            {
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(userName.Text, passWord.Text, domain.Text);
                svc.ClientCredentials.Windows.ClientCredential = credentials;
            }
            else
            {
                svc.ClientCredentials.UserName.UserName = userName.Text;
                svc.ClientCredentials.UserName.Password = passWord.Text;
            }

            return svc;
        }
        private void go_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                ServiceBusAdapter.ServiceBusAdapterClient svc = GetServiceProxy();

                // basic info
                ServiceBusAdapter.ConstituentAdd constit = new ServiceBusAdapter.ConstituentAdd();
                constit.FirstName = firstName.Text;
                constit.LastOrOrganizationName = lastName.Text;
                constit.ConstituentType = ServiceBusAdapter.ConstituentType.Individual;
                constit.Gender = (ServiceBusAdapter.ConstituentGenderType)Enum.Parse(typeof(ServiceBusAdapter.ConstituentGenderType), gender.Text);
                constit.Birthdate = birthDate.Value;

                // addresses
                if (includeAddress.Checked)
                {
                    List<ServiceBusAdapter.AddressData> addresses = new List<ServiceBusAdapter.AddressData>();
                    ServiceBusAdapter.AddressData address = new ServiceBusAdapter.AddressData();
                    address.AddressBlock = addressBlock.Text;
                    address.City = city.Text;
                    address.State = state.Text;
                    address.PostalCode = zip.Text;
                    address.IsPrimary = true;
                    address.AddressType = addressType.Text;
                    address.ID = addressID.Text;
                    addresses.Add(address);
                    constit.Addresses = addresses.ToArray<ServiceBusAdapter.AddressData>();
                }

                // phones
                if (includePhone.Checked)
                {
                    List<ServiceBusAdapter.PhoneData> phones = new List<ServiceBusAdapter.PhoneData>();
                    ServiceBusAdapter.PhoneData phone = new ServiceBusAdapter.PhoneData();
                    phone.PhoneNumber = phoneNumber.Text;
                    phone.PhoneType = phoneType.Text;
                    phone.IsPrimary = true;
                    phones.Add(phone);
                    constit.Phones = phones.ToArray<ServiceBusAdapter.PhoneData>();
                }

                // emails
                if (includeEmail.Checked)
                {
                    List<ServiceBusAdapter.EmailData> emails = new List<ServiceBusAdapter.EmailData>();
                    ServiceBusAdapter.EmailData email = new ServiceBusAdapter.EmailData();
                    email.EmailAddress = emailAddress.Text;
                    email.EmailAddressType = emailType.Text;
                    email.IsPrimary = true;
                    emails.Add(email);
                    constit.EmailAddresses = emails.ToArray<ServiceBusAdapter.EmailData>();
                }

                //  make the call
                string result;
                Guid correlationID = svc.AddConstituent("TestClient", false, constit, null, out result);
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Result: " + result + Environment.NewLine + "Correlation ID: " + correlationID.ToString());
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Exception: " + ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            
            string cr = Environment.NewLine;

            // Establish the soap service object
            BBECAddressChanges.ListService svc = new BBECAddressChanges.ListService();

            // Establish credentials and associate with the soap client
            System.Net.ICredentials credentials = new System.Net.NetworkCredential("EsbTest_34271", "Password1");
            svc.Credentials = credentials;

            // Set up a request object.  GetRowsRequest allows filtering.  GetAllRowsRequest does not; it just returns everything
            BBECAddressChanges.GetRowsRequest request = new BBECAddressChanges.GetRowsRequest();

            // Establish filter criteria using the strongly-typed Filter property of the request object
            // All data lists that are setup as RSS feeds include the DATAWINDOWOPEN and DATAWINDOWCLOSE filters.
            // This is where WV would pass into the DATAWINDOWOPEN filter the last time they ran the process (or, perhaps
            // more accurately, one second AFTER the last time they ran the process) and would pass into DATAWINDOWCLOSE
            // the current date/time.
            BBECAddressChanges.FilterData filter = new BBECAddressChanges.FilterData();
            
            // if you want just addresses ADDED since a particular date/time (this filter will pull records where the DATEADDED is GREATER THAN the value provided here)
            filter.DATECHANGED = addressAddsUpdatesDate.Value;   // new DateTime(2000, 1, 5);    // pass the date/time when you last called this operation

            // if you want to get all addresses ADDED or UPDATED since a particular date/time (this filter also operate as GREATER THAN the value provided)
            //filter.DATECHANGED = new DateTime(2012, 1, 5);    // pass the date/time when you last called this operation

            request.Filter = filter;

            // Call the GetRows method of the soap client and get the resulting reply object
            BBECAddressChanges.GetRowsReply reply = svc.GetRows(request);

            // Iterate through the results
            if (reply.StatusOK && reply.TotalAvailableRows > 0)
            {
                textBox1.Text = "Results:" + Environment.NewLine;
                foreach (BBECAddressChanges.ListRow row in reply.Rows)
                {
                    textBox1.Text += string.Format("  Constituent: {0} ({1}){2}  Address ID: {3}{4}  Address: {5}{6}  City, State  ZIP: {7}, {8}  {9}{10}  Country: {11}{12}{13}",
                        row.ConstituentName, row.ConstituentLookupID, cr, row.AddressLookupID, cr, row.AddressBlock, cr, row.City, row.State,
                        row.PostalCode, cr, row.Country, cr, cr);
                }
            }
            else
            {
                textBox1.Text = "No results.";
            }

            Cursor.Current = Cursors.Default;
        }

        private void goFP_Click(object sender, EventArgs e)
        {
            ServiceBusAdapter.ServiceBusAdapterClient svc = GetServiceProxy();
            ServiceBusAdapter.FundraisingPurposeAdd fp = new ServiceBusAdapter.FundraisingPurposeAdd();
            string result = string.Empty;

            fp.Name = fundraisingPurposeName.Text;
            fp.PurposeType = fundraisingPurposeType.Text;
            fp.LookupId = fundraisingPurposeLookupID.Text;

            Cursor.Current = Cursors.WaitCursor;

            try
            {
                svc.AddFundraisingPurpose("TestClient", false, fp, out result);
                MessageBox.Show(result);
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default; 
                MessageBox.Show(ex.Message);
            }
            Cursor.Current = Cursors.Default;
        }

        private void UpdateConstituentButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            string result = "";
            
            ServiceBusAdapter.ServiceBusAdapterClient svc = GetServiceProxy();
            ServiceBusAdapter.ConstituentUpdate cu = new ServiceBusAdapter.ConstituentUpdate();
            cu.LookupID = constituentLookupID_Update.Text;

            ServiceBusAdapter.AddressDataUpdate adu = new ServiceBusAdapter.AddressDataUpdate();
            if (addressID_Update.Text != "")
            {
                adu.Action = ServiceBusAdapter.ActionType.Update;
                adu.ID = addressID_Update.Text;
            }
            else
            {
                adu.Action = ServiceBusAdapter.ActionType.Add;
            }

            adu.AddressBlock = addressBlock_Update.Text;
            adu.City = city_Update.Text;
            adu.State = state_Update.Text;
            adu.PostalCode = postalCode_Update.Text;
            adu.AddressType = addressType_Update.Text;
            List<ServiceBusAdapter.AddressDataUpdate> addresses = new List<ServiceBusAdapter.AddressDataUpdate>();
            addresses.Add(adu);
            cu.Addresses = addresses.ToArray<ServiceBusAdapter.AddressDataUpdate>();
            try
            {
                Guid correlationID = svc.UpdateConstituent("TestClient", false, cu, out result);
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Result: " + result + Environment.NewLine + "Correlation ID: " + correlationID.ToString());
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show(ex.Message);
            }
        }

        private void useEsbTestEnvironmentButton_Click(object sender, EventArgs e)
        {
            endPointAddress.Text = "https://designsandbox2.blackbaud.com/SvcBusAdapter_WorldVision_34271_ESB/AdapterService.xamlx/soap12";
            passWord.Text = "Password1";
            domain.Text = "BIDEV";
        }

        private void getErrorCodesButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            errorCodes.Text = "";
            ServiceBusAdapter.ServiceBusAdapterClient svc = GetServiceProxy();
            errorCodes.Text = svc.GetErrorCodes();
            Cursor.Current = Cursors.Default;
        }
    }
}
